package com.songshuai.webapi.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.webapi.common.redis.RedisUtil;
import com.songshuai.webapi.login.client.AuthServiceClient;
import com.songshuai.webapi.login.dto.JWT;
import com.songshuai.webapi.login.dto.LoginDTO;
import com.songshuai.webapi.login.dto.RespDTO;
import com.songshuai.webapi.login.dto.UserLoginDto;
import com.songshuai.webapi.login.model.YxUsers;
import com.songshuai.webapi.login.service.CrmLoginService;
import com.songshuai.webapi.login.utils.HttpClientUtil;
import com.songshuai.webapi.login.utils.RegexUtil;
import com.songshuai.webapi.login.utils.Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Service
public class CrmLoginServiceImpl extends BaseLoginService implements CrmLoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.application.name}")
    String application;
    @Value("${sms.url}")
    String smsUrl;
    @Value("${sms.soltkey}")
    String smsKey;




    @Resource
    AuthServiceClient authServiceClient;

    /*
  CRM系统登录
   */
    @Override
    public RespDTO crmLogin(UserLoginDto user) {
        Integer type = user.getType();
        int integer = RegexUtil.validPhoneOrMail(user.getUsername());
        UserLoginDto   yxUsers=getYxUser(integer,user.getUsername(),type);
        if(null==yxUsers){
            return  RespDTO.onFail("用户不存在");
        }

        if(1==type){//用户名密码，手机号密码方式登录
            //验证用户名密码匹配
            if(!Util.md5(user.getPassword()).substring(0,20).equalsIgnoreCase(yxUsers.getPassword())){
                return  RespDTO.onFail("用户名或密码错误");
            }
            //从远程拿到token
            return getJWTToken(user,yxUsers);


        }else if(2==type){//手机验证码登录
            //验证验证码的有效性
            redisUtil.setSuffixKey("crm");
            String verification =redisUtil.getString("code:"+user.getUsername());
            if(StringUtils.isNotBlank(verification)){
                if(user.getPassword().equalsIgnoreCase(verification)){
                    //从远程拿token
                    return getJWTToken(user,yxUsers);
                }else{
                    return  RespDTO.onFail("验证码错误");
                }

            }else{
                return  RespDTO.onFail("验证码失效");
            }
        }else{
            return  RespDTO.onFail("登录类型不正确");
        }
    }
    //发送验证码
    @Override
    public RespDTO sentVerificationCode(String mobile) {
        int integer = RegexUtil.validPhoneOrMail(mobile);
        int code = (int) ((Math.random() * 9 + 1) * 1000);
        if(1==integer){
            redisUtil.setSuffixKey("crm");
            redisUtil.set("code:"+mobile,code,300);//验证码五分钟过期
          /*  Map<String,Object> jsonObject=new HashMap<>();
            jsonObject.put("mobile",mobile);
            jsonObject.put("message","验证码是 "+code);
            jsonObject.put("operator_id","8765446");*/

            //调短信网关发短信
            long time=new Date().getTime();
            String s = HttpClientUtil.doPostJson(smsUrl, "{\"mobile\":\""+mobile+"\",\"message\":\"验证码是 "+code+"\",\"operator_id\":\"8765446\"}", Util.md5(smsKey + time), String.valueOf(time));
            if(StringUtils.isNotBlank(s)){
                JSONObject result = JSON.parseObject(s);
                Integer vercode = result.getInteger("code");
                if(0==vercode){
                    return RespDTO.onSuc(code);
                }else{
                    return RespDTO.onFail("发送失败");
                }

            }else{
                return  RespDTO.onFail("获取验证码失败");
            }


        }else{
           return RespDTO.onFail("手机格式不正确");
        }
    }

    @Override
    public int resetPassword(String username, String password) {
        Example example=new Example(YxUsers.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mobile",username);
        YxUsers par=new YxUsers();
        par.setPassword(Util.md5(password).substring(0,20));
        int i = usersMapper.updateByExampleSelective(par, example);
        redisUtil.setSuffixKey("crm");
        redisUtil.del(username);
        return i;
    }


    public RespDTO getJWTToken(UserLoginDto user,UserLoginDto yxUsers){
         BASE64Encoder encoder = new BASE64Encoder();
         String auth=null;
         try {
             auth= encoder.encode((application + ":123456").getBytes("UTF-8"));
         } catch (UnsupportedEncodingException e) {
             return  RespDTO.onFail(e.toString());
         }
         JWT jwt = authServiceClient.getToken("Basic "+auth, "password", user.getUsername(), yxUsers.getPassword());
         // 获得用户菜单
         if(null==jwt){
             return RespDTO.onFail("获取token失败，稍后重试");
         }
         LoginDTO loginDTO=new LoginDTO();
         yxUsers.setPassword("");
         loginDTO.setUser(yxUsers);
         loginDTO.setToken(jwt.getAccess_token());
         redisUtil.setSuffixKey("crm");
         redisUtil.set(user.getUsername(),yxUsers.getId());
         redisUtil.set(String.valueOf(yxUsers.getId()),jwt.getAccess_token(),1800);
         System.out.println(user.getUsername()+":"+redisUtil.getString(user.getUsername()));
         redisUtil.setSuffixKey("permission");
         redisUtil.set(user.getUsername(),yxUsers.getId());
         redisUtil.set(String.valueOf(yxUsers.getId()),jwt.getAccess_token(),1800);
         return RespDTO.onSuc(loginDTO);
     }
}
